/*
 * ========================================================================
 * Copyright 2008 University of Washington
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * ========================================================================
 */

package ws;

import ExchangeEventConverter.iCal4j;
import com.microsoft.schemas.exchange.services._2006.types.CalendarItemType;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import org.apache.log4j.Logger;

/**
 *
 * @author nickchen
 */
public class ExchangeiCalServlet extends HttpServlet {
    private static Logger  logger = Logger.getLogger( ExchangeCalendarRetriever.class );
    
    /** 
    * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
    * @param request servlet request
    * @param response servlet response
    */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        logger.debug("doing request from: "+request.getRemoteAddr());
        PrintWriter out = response.getWriter();
        try {
            String domain       = "";
            if( getServletContext().getInitParameter("domain") != null ) {
                domain = getServletContext().getInitParameter("domain");
            }
            
            String auth_head    = request.getHeader("Authorization");
            if (auth_head != null && auth_head.startsWith("Basic")) {
                String usernpass    = new String(org.apache.commons.codec.binary.Base64.decodeBase64((auth_head.substring(6).getBytes())));
                String user         = usernpass.substring(0, usernpass.indexOf(":"));
                String password     = usernpass.substring(usernpass.indexOf(":") + 1);
                String exchangeUserEmail   = request.getParameter("user");
                String daysBack            = request.getParameter("b");
                String daysAhead           = request.getParameter("a");
                try {
                    // easier testing like this. change back for final production deployment
                    // response.setContentType("text/plain;charset=UTF-8");
                    response.setContentType("text/calendar;charset=UTF-8");
                    response.setHeader("Content-Disposition:", "attachment; filename=\"exchange_ical.ics\"");
                    ExchangeCalendarRetriever retriever = 
                    new ExchangeCalendarRetriever(ExchangeCalendarRetriever.class.getResource("/"), domain, user, password);
                    
                    ArrayList<CalendarItemType> calenderItems = retriever.getCalender(exchangeUserEmail, daysBack, daysAhead);
                    out.print( iCal4j.convertCalendarItemType( calenderItems ));
                    response.flushBuffer();
                } catch ( Exception ex ) {
                    ex.printStackTrace();
                    logger.error(ex);
                    if( ex.getLocalizedMessage().indexOf("Unauthorized") != -1 ) {
                        response.setStatus(response.SC_UNAUTHORIZED);
                        response.setHeader("WWW-Authenticate", "Basic realm=\"exchange\"");
                        response.flushBuffer();
                        return;
                    } else if ( ex.getLocalizedMessage().indexOf("ErrorFolderNotFound") != -1 ) {
                        logger.error("returning SC_NOT_FOUND: "+ex.getLocalizedMessage());
                        response.setStatus(response.SC_NOT_FOUND);
                        response.setContentType("text/plain;charset=UTF-8");
                        out.println( ex.toString() );
                        response.flushBuffer();
                        return;
                    } else {
                        logger.error("returning SC_BAD_GATEWAY: "+ex.getLocalizedMessage());
                        response.setStatus(response.SC_BAD_GATEWAY);
                        response.setContentType("text/plain;charset=UTF-8");
                        out.println( ex.toString() );
                        response.flushBuffer();
                        return;
                    }
                }
            } else {
                response.setStatus(response.SC_UNAUTHORIZED);
                response.setHeader("WWW-Authenticate", "Basic realm=\"exchange\"");
                response.flushBuffer();
                return;
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            logger.error(ex);
        } finally {
            out.close();
        }
    } 

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
    * Handles the HTTP <code>GET</code> method.
    * @param request servlet request
    * @param response servlet response
    */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    } 

    /** 
    * Handles the HTTP <code>POST</code> method.
    * @param request servlet request
    * @param response servlet response
    */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
    * Returns a short description of the servlet.
    */
    @Override
    public String getServletInfo() {
        return "Exchange Calender";
    }// </editor-fold>

}
